package com.siecomzg.transport.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import com.google.protobuf.InvalidProtocolBufferException;
import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.proto.Message;
import com.siecomzg.tool.LogUtil;
import com.siecomzg.transport.CommonClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;

/**
 * Created  on 2016/6/13.
 */
public class BlueClient extends CommonClient {

    public static final String PROTOCOL_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    public static final String TAG = BlueClient.class.getSimpleName();
    private static BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private static BluetoothSocket socket = null;
    private static InputStream inputStream = null;
    private static OutputStream outputStream = null;
    private static ListenThread listenThread = null;
    private volatile boolean flag = false;
    public interface OnReceiveListen {

        public void onMessageReceive(Message.siecomproto msg, String message);

        public void onError(Throwable e);
    }

    public OnReceiveListen onReceiveListen = null;

    public BlueClient() {
        if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

    public void connect(String mac) throws IOException {

        BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac);
        connect(device);

    }

    public void setOnListen(OnReceiveListen onReceiveListen) {

        this.onReceiveListen = onReceiveListen;

    }

    public void connect(BluetoothDevice device) throws IOException {

        close();
        socket = device.createRfcommSocketToServiceRecord(UUID.fromString(PROTOCOL_UUID));
        LogUtil.e(TAG, "cilent connect...");
        socket.connect();
        flag = false;
        LogUtil.e(TAG, "connect success !");
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();

    }

    public void disConnect(){
        socket = null;
    }

    public void listen(boolean forceInterrupted) {
        if (listenThread != null) {
            if (forceInterrupted) {
                listenThread.setStopFlag();
                listenThread = null;
            } else {
                return;
            }
        }
        listenThread = new ListenThread();
        listenThread.start();
    }


    public class ListenThread extends Thread {
        private boolean stopFlag = false;
        ArrayList mByteArray = new ArrayList<Byte>();
        int totalLen = 0;
        public void setStopFlag() {

            this.stopFlag = true;
        }

        int len = -1;
        @Override
        public void run() {
            synchronized (this) {
                byte[] recByte = null;
                byte[] sendByte = null;
                byte[]  fina = null;
                while (!stopFlag) {
                    try {
                        len = inputStream.available();
                        if(len > 0){
                            totalLen += len;
//                            LogUtil.e(TAG,"收到的msg len--" + len + "--total:" + totalLen);
                             recByte = new byte[len];
                            inputStream.read(recByte);
                            for(int j = 0; j< len;j++){
                                mByteArray.add(recByte[j]);
                            }
                             sendByte = new byte[totalLen];
                            for(int m = 0;m < sendByte.length; m++){
                                sendByte[m] = (byte)mByteArray.get(m);
                            }

                            if(sendByte[0] == 0x02) {
                                int sendLen = (sendByte[1] & 0xFF) * 256 + (sendByte[2] & 0xFF);
                                if ((sendLen + 5) == totalLen ){
                                    fina = new byte[sendLen];
                                    System.arraycopy(sendByte,3,fina,0,sendLen);

                                    Message.siecomproto msg = Message.siecomproto.parseFrom(fina);
                                    if((msg.getCmd() == ConstDefine.DEVICE_SERIAL_NO_RESPOND ||
                                            msg.getCmd() == ConstDefine.GET_CODENAME_RESPOND)
                                            && msg.getRespond().isEmpty()){
                                        continue;
                                    }
//                                      LogUtil.e(TAG,"接收到数据byte：" + ByteTool.byte2hex(sendByte));
                                    LogUtil.e(TAG,"接收到数据msg：" + msg.toString());
                                    if (onReceiveListen != null) {
                                        onReceiveListen.onMessageReceive(msg,"");
                                        totalLen = 0;
                                        mByteArray.clear();
                                    }
                                }
                            }


                        }

                    } catch (InvalidProtocolBufferException ex) {
//                        ex.printStackTrace();
                        LogUtil.e(TAG,flag+"-- exception ==" + ex.getMessage().toString());
//                        if(!flag) {
//                            if (onReceiveListen != null) {
//                                onReceiveListen.onError(ex);
//                            }
//                        }
//                        SystemClock.sleep(100);

                    } catch (IOException e) {
                        LogUtil.e("Throwable2",e.getMessage());
                        e.printStackTrace();
                        if (onReceiveListen != null)
                            onReceiveListen.onError(e);
                        break;
                    }
                    catch (NullPointerException ee) {
                        LogUtil.e("Throwable3",ee.getMessage());
//                        if (onReceiveListen != null)
//                            onReceiveListen.onError(ee);
                        break;
                    }
                }
            }
        }
    }

    public void close() {
        try {
            if (inputStream != null) {
                inputStream.close();
                flag = true;
            }
            inputStream = null;
            if (outputStream != null) {
                outputStream.close();
                flag = true;
            }
            outputStream = null;
            if (socket != null) {
                socket.close();
                flag = true;
            }
            socket = null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    byte b[] = null;
    byte allData[] = null;
    public void sendToRemote(Message.siecomproto msg,String msgStr) throws IOException {

        synchronized (this) {
            try {
                b = msg.toByteArray();
                int len = b.length;
                allData = new byte[len + 5];
                allData[0] = 0x02;
                allData[1] = (byte)(len / 256);
                allData[2] = (byte)(len % 256);
                System.arraycopy(b,0,allData,3,len);
                allData[len + 3] = 0x00;
                allData[len + 4] = 0x00;
//                LogUtil.e(TAG,"send == " + ByteTool.byte2hex(allData));
                outputStream.write(allData);
//                outputStream.write(msg.toByteArray());
                outputStream.flush();
            } catch (IOException e) {
                if (onReceiveListen != null)
                    onReceiveListen.onError(e);
                e.printStackTrace();
                throw e;
            }

        }
    }

}
